package zzjson.rabbitmq.confirm;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmListener;
import com.rabbitmq.client.Connection;
import zzjson.rabbitmq.BaseRabbitMq;

import java.io.IOException;

/**
 * <p>****************************************************************************</p>
 * <p><b>Copyright © 2010-2019 shuncom team All Rights Reserved<b></p>
 * <ul style="margin:15px;">
 * <li>Description : zzjson.rabbitmq.confirm</li>
 * <li>Version     : 1.0.0</li>
 * <li>Creation    : 2019年04月29日</li>
 * <li>@author     : zzy0_0</li>
 * </ul>
 * <p>****************************************************************************</p>
 */
public class AsyncConfirmProducer {
	private final static String QUEUE_NAME = "ORIGIN_QUEUE";

	public static void main(String[] args) throws IOException {
		Connection conn = BaseRabbitMq.getConn();
		Channel channel = conn.createChannel();

		String msg = "Hello world, Rabbit MQ, Async Confirm";

		channel.queueDeclare(QUEUE_NAME, false, false, false, null);

		// 开启发送方确认模式
		channel.confirmSelect();
		for (int i = 0; i < 10; i++) {
			//	发送消息
			channel.basicPublish("", QUEUE_NAME, null, (msg + "-" + i).getBytes());
		}

		// 这里不会打印所有响应的ACK；ACK可能有多个，有可能一次确认多条，也有可能一次确认一条
		// 异步监听确认和未确认的消息
		// 如果要重复运行，先停掉之前的生产者，清空队列
		channel.addConfirmListener(new ConfirmListener() {
			@Override
			public void handleAck(long deliveryTag, boolean multiple) throws IOException {
				System.out.println("Broker未确认消息，标识：" + deliveryTag);

			}

			@Override
			public void handleNack(long deliveryTag, boolean multiple) throws IOException {
				System.out.println(String.format("Broker已确认消息，标识：%d，多个消息：%b", deliveryTag, multiple));

			}
		});

		System.out.println("程序执行完成");

		// BaseRabbitMq.close(channel, conn);
	}
}